package com.nexus.plugin.amqp.service;

import com.nexus.plugin.amqp.annotion.RabbitSender;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Date 2025/9/25 03:09
 * @Author luzhengning
 **/
@Service
public class RabbitService {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 创建消息队列，根据消息发送注解
     *
     * @Date 2025/9/25 03:47
     * @Author luzhengning
     **/
    public boolean createQueue(RabbitSender rabbitSender) throws IOException, TimeoutException {
        String exchangeName = rabbitSender.exchange();
        String queueName = rabbitSender.queue();
        String routingKey = rabbitSender.routingKey();

        Connection connection=null;
        Channel channel=null;
        try {
            connection = rabbitTemplate.getConnectionFactory().createConnection().getDelegate();
            channel = connection.createChannel();
            channel.exchangeDeclare(exchangeName, rabbitSender.exchangeType(), rabbitSender.persistent(), false, null);
            channel.queueDeclare(queueName, rabbitSender.persistent(), false, false, null);
            channel.queueBind(queueName, exchangeName, routingKey);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(channel!=null)channel.close();
        }
        return true;
    }
}